/*
 * Copyright 2009 IT Mill Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.iknow.main;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.iknow.db.User;
import org.iknow.db.util.HibernateUtil;

import com.vaadin.Application;
import com.vaadin.service.ApplicationContext.TransactionListener;
import com.vaadin.terminal.gwt.server.HttpServletRequestListener;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Label;
import com.vaadin.ui.Window;
import com.vaadin.ui.Window.CloseEvent;

/**
 * The Application's "main" class
 */
public class MainApplication extends Application implements HttpServletRequestListener,Window.CloseListener
{
	/**
	 * 
	 */
	private static final long serialVersionUID = -5098169454563376171L;
	private Window window;
	private static ThreadLocal<MainApplication> threadLocal = new ThreadLocal<MainApplication>(); 


    @Override
    public void init()
    {
        window = new Window("My Vaadin Application");
        setMainWindow(window);
        Button button = new Button("Click Me");
        button.addListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                window.addComponent(new Label("Thank you for clicking"));
            }
        });
        window.addComponent(button);
        
        Button button2 = new Button("Click Me 2");
        window.addComponent(button2);
        User u=new User();
        u.setUsername("test01");
        u.setPassword("test01");
        HibernateUtil.getSession().save(u);
        HibernateUtil.getSession().getTransaction().commit();
        HibernateUtil.getSession().close();
        
        attachVaadinTransactionListener();
    }
    
    /**
	 * We are using session-per-request pattern with Hibernate. By using
	 * Vaadin's transaction listener we can easily ensure that session is closed
	 * on each request without polluting our program code with extra logic.
	 */
	private void attachVaadinTransactionListener() {
		getContext().addTransactionListener(new TransactionListener() {
			/**
			 * 
			 */
			private static final long serialVersionUID = -7727149551252570994L;

			public void transactionEnd(Application application,
					Object transactionData) {
				// Transaction listener gets fired for all (Http) sessions
				// of Vaadin applications, checking to be this one.
				if (application == MainApplication.this) {
					HibernateUtil.closeSession();
					threadLocal.remove();
				}
			}

			public void transactionStart(Application application,
					Object transactionData) {
			}
		});
	}

	public void windowClose(CloseEvent e) {
		// TODO Auto-generated method stub
		
	}

	public void onRequestStart(HttpServletRequest request,
			HttpServletResponse response) {
		MainApplication.setInstance(this);
	}

	public void onRequestEnd(HttpServletRequest request,
			HttpServletResponse response) {
		threadLocal.remove();
	}
	
	// @return the current application instance	  	
	public static MainApplication getInstance() {
		return threadLocal.get();
	}
	
	public static void setInstance(MainApplication application) {
		if(getInstance()==null)
			threadLocal.set(application);
	}
    
}
